<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\service\CategoryService;
use app\service\InnerPurchaseService;
use app\service\ProcessService;
use app\service\StoreBackService;
use think\facade\Db;
use think\facade\Validate;
use think\Request;
use app\service\HouseService;
use app\service\HouseInService;
use app\service\HouseOutService;
use app\service\GoodsService;
use app\service\UserService;

class HouseController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', env('pager.default.size'));
      $data['process'] = $request->param('process', '');
      $data['category_id'] = $request->param('category_id', '');
      $validate = Validate::rule([
        'process' => 'require',
      ])->message([
        'process.require' => 'process必填'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $conditions = [];
      if(strlen($data['process']) > 0){
        $conditions[] = ['h.process',$data['process'],'='];
      }
      if(strlen($data['category_id']) > 0){
        $conditions[] = ['g.category_id',$data['category_id'],'='];
      }
      $list = HouseService::getInstance()->getHouseJoinGoods($conditions);
      // 获取分类
      $category = CategoryService::getInstance()->getCategoryByCondition([['base', 0, '=']]);
      $category = array_column($category, 'category_name', 'id');
      foreach ($list as &$value) {
        $value['category'] = isset($category[$value['category_id']]) ? $category[$value['category_id']] : '';
      }
      // 分页
      $count = count($list); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];

      $data = array_slice($list, $start, intval($pageSize));
      return $this->send200ResponseWithPager($data,$pager);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
      $data = [];
      $data['goods_id'] = $request->param('goods_id','');
      $data['count_in'] = $request->param('count_in','');
      $data['price_in'] = $request->param('price_in','');
      $process = $request->param('process', '');
      $data['comment'] = $request->param('comment','');
      $data['supplier'] = $request->param('supplier','');
      if ($process === '') {
        return $this->send400Response('process不能为空');
      }
      $validate = Validate::rule([
        'goods_id' => 'require',
        'count_in' => 'require',
        'price_in' => 'require',
      ])->message([
        'goods_id.require' => '商品不能为空',
        'count_in.require' => '数量不能为空',
        'price_in.require' => '价格不能为空'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $result = HouseService::getInstance()->createHouse($process, $data);
      if ($result['status']) {
        return $this->send200Response('ok');
      } else {
        return $this->send400Response($result['msg']);
      }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
      $conditions[] = ['h.id', $id, '='];
      $house = HouseService::getInstance()->getHouseJoinGoods($conditions);
      if (!$house || !isset($house[0]) || !$house[0]) {
        return $this->send400Response('该数据不存在');
      }
      return $this->send200Response($house[0]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
      $data = [];
      $data['process'] = $request->param('process','');
      $data['sale_time'] = $request->param('sale_time','');
      $data['count'] = $request->param('count','');
      $data['comment'] = $request->param('comment','');
      $data['type'] = $request->param('type','');
      $data['base'] = $request->param('base','');
      $data['sell_price'] = $request->param('sell_price','');

      $validate = Validate::rule([
        'process' => 'require',
        'sale_time' => 'require',
        'count' => 'require',
        'type' => 'require'
      ])->message([
        'process.require' => 'process不能为空',
        'sale_time.require' => '日期不能为空',
        'count.require' => '数量不能为空',
        'type.require' => '售出类型不能为空'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      // 售出类型（1加工，2售出）
      if ($data['type'] == 2) {
        if ($data['base'] == '') {
          return $this->send400Response('请选择售出门店');
        } elseif ($data['sell_price'] === '') {
          return $this->send400Response('请输入售出价格');
        }
      }
      $result = HouseService::getInstance()->updateHouse($id, $data);
      if ($result['status']) {
        return $this->send200Response('ok');
      } else {
        return $this->send400Response($result['msg']);
      }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function sell(Request $request, $id) {
      $data = [];
      $data['sale_time'] = $request->param('sale_time','');
      $data['count'] = $request->param('count','');
      $data['comment'] = $request->param('comment','');
      $data['base'] = $request->param('base','');
      $data['sell_price'] = $request->param('sell_price','');
      $validate = Validate::rule([
        'sale_time' => 'require',
        'base' => 'require',
        'count' => 'require',
        'sell_price' => 'require'
      ])->message([
        'base.require' => 'base不能为空',
        'sale_time.require' => '日期不能为空',
        'count.require' => '数量不能为空',
        'sell_price.require' => '售价不能为空'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      if (!$data['sell_price']) {
        return $this->send400Response('售价不能为空');
      }
      $result = HouseService::getInstance()->sellProduct($id, $data);
      if ($result['status']) {
        return $this->send200Response('ok');
      } else {
        return $this->send400Response($result['msg']);
      }
    }


    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 获取库存数量
     */
    public function houseCount(Request $request){
      $nums = $request->param('nums',[]);
      if (!$nums) {
        return $this->send400Response('缺少nums参数');
      }
      $data = HouseService::getInstance()->getHouseCount($nums);
      return $this->send200ResponseWithPager($data);
    }

    /**
     * 批量新增库存
     */
    public function houseMultiAdd(Request $request){
      $data['data'] = $request->param('data',[]);
      $data['process'] = $request->param('process','');
      $data['supplier'] = $request->param('supplier','');
      $data['default_time'] = $request->param('default_time','');
      $validate = Validate::rule([
        'data' => 'require',
        'process' => 'require',
        'supplier' => 'require',
        'default_time' => 'require'
      ])->message([
        'data.require' => '缺少data参数',
        'process.require' => 'process不能为空',
        'supplier.require' => 'supplier不能为空',
        'default_time.require' => 'default_time不能为空'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $result = HouseService::getInstance()->createMultiHouse($data);
      if ($result['status']) {
        return $this->send200Response('ok');
      } else {
        return $this->send400Response($result['msg']);
      }
    }

    /**
     * 出库信息删除
     */
    public function deleteHouseOut(Request $request){
      $id = $request->param('id','');
      $type = $request->param('type','');
      if ($id === '') {
        return $this->send400Response('缺少id参数');
      }
      if ($type === '') {
        return $this->send400Response('缺少type参数');
      }
      $result = HouseOutService::getInstance()->deleteHouseOut($id, $type);
      if (!$result['status']) {
        return $this->send400Response($result['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 获取进出库明细
     */
    public function houseInOut(Request $request){
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', env('pager.default.size'));
      $type = $request->param('type', []);
      $process = $request->param('process', '');
      $base = $request->param('base', '');
      $startTime = $request->param('startTime', '');
      $endTime = $request->param('endTime', '');
      $startTime = $startTime ? date('Y-m-d', strtotime($startTime)) : '';
      $endTime = $endTime ? date('Y-m-d', strtotime($endTime) + (24 * 60 * 60)) : '';
      $list = [];
      // process = '' type有1则process=0 type有2则process=1
      // process = 1  type有1则无视 type有2则process=1
      // process = 0  type有2则无视 type有1则process=0

      // 入库
      if ((!$type || in_array(1, $type) || in_array(2, $type)) && !$base) {
        $condHouseIn = [];
        $condHouseIn[] = ['o.status', 1, '='];
        if ($process !== '') {
          $condHouseIn[] = ['g.process',$process,'='];
        }
        if ($type && in_array(1, $type) && !in_array(2, $type)) {
          $condHouseIn[] = ['g.process',0,'='];
        } elseif ($type && in_array(2, $type) && !in_array(1, $type)) {
          $condHouseIn[] = ['g.process',1,'='];
        }
        if ($startTime) {
          $condHouseIn[] = ['o.default_time', $startTime, '>='];
        }
        if ($endTime) {
          $condHouseIn[] = ['o.default_time', $endTime, '<'];
        }
        $houseInList = HouseInService::getInstance()->getHouseInJoinGoods($condHouseIn);
        foreach ($houseInList as $v1) {
          $list[] = [
            'time' => $v1['default_time'],
            'type' => $v1['process'] ? '生产' : '采购',
            'process' => $v1['process'] ? '成品' : '原料',
            'sell_number' => $v1['house_in_number'],
            'category_name' => $v1['category_name'],
            'name' => $v1['name'],
            'unit' => $v1['unit'],
            'count' => $v1['count'],
            'price' => $v1['price'],
            'total_amount' => $v1['total_amount'],
            'sell_price' => '',
            'total_price' => '',
            'basename' => '',
            'comment' => $v1['comment'],
            'datesort' => strtotime($v1['default_time'])
          ];
        }
      }
      // 出库
      if (!$type || in_array(3, $type)) {
        $condHouseOut = [];
        $condHouseOut[] = ['h.status', 1,'='];
        if ($process !== '') {
          $condHouseOut[] = ['h.process', $process, '='];
        }
        if ($base !== '') {
          $condHouseOut[] = ['h.base', $base, '='];
        }
        if ($startTime) {
          $condHouseOut[] = ['h.sale_time', $startTime, '>='];
        }
        if ($endTime) {
          $condHouseOut[] = ['h.sale_time', $endTime, '<'];
        }
        $houseOutList = HouseOutService::getInstance()->getHouseOutJoinGoods($condHouseOut);
        foreach ($houseOutList as $v2) {
          $list[] = [
            'time' => $v2['sale_time'],
            'type' => $v2['type'] === 1 ? '加工消耗' : '售出',
            'process' => $v2['process'] ? '成品' : '原料',
            'sell_number' => $v2['sell_number'],
            'category_name' => $v2['category_name'],
            'name' => $v2['name'],
            'unit' => $v2['unit'],
            'count' => $v2['count'],
            'price' => $v2['price'],
            'total_amount' => round($v2['count'] * $v2['price'], 2),
            'sell_price' => $v2['sell_price'],
            'total_price' => round($v2['count'] * $v2['sell_price'], 2),
            'basename' => $v2['basename'],
            'comment' => $v2['comment'],
            'datesort' => strtotime($v2['sale_time'])
          ];
        }
      }
      // 退货
      if (!$type || in_array(4, $type)) {
        $condBack = [];
        $condBack[] = ['so.status', 1,'='];
        if ($startTime) {
          $condBack[] = ['so.back_time', $startTime, '>='];
        }
        if ($endTime) {
          $condBack[] = ['so.back_time', $endTime, '<'];
        }
        if ($base !== '') {
          $condBack[] = ['sb.base', $base, '='];
        }
        if ($process !== '') {
          $condBack[] = ['g.process', $process, '='];
        }
        $backList = StoreBackService::getInstance()->getBackJoinStore($condBack);
        foreach ($backList as $v3) {
          $list[] = [
            'time' => $v3['back_time'],
            'type' => '退货',
            'process' => $v3['process'] ? '成品' : '原料',
            'sell_number' => $v3['apply_number'],
            'category_name' => $v3['category_name'],
            'name' => $v3['name'],
            'unit' => $v3['unit'],
            'count' => $v3['count'],
            'price' => $v3['price'] ? $v3['price'] : 0,
            'total_amount' => round($v3['count'] * $v3['price'], 2),
            'sell_price' => '',
            'total_price' => '',
            'basename' => $v3['basename'],
            'comment' => '',
            'datesort' => strtotime($v3['back_time'])
          ];
        }
      }
      // 排序
      foreach ($list as $key=>$value){
        $dateSort[$key] = $value['datesort'];
      }
      if ($list) {
        array_multisort($dateSort,SORT_NUMERIC,SORT_DESC, $list);
      }
      // 分页
      $count = count($list); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];

      $data = array_slice($list, $start, intval($pageSize));
      return $this->send200ResponseWithPager($data,$pager);
    }
}
